import { initTRPC } from "@trpc/server";
import { headers } from "next/headers";
import { cache } from "react";
export const createTRPCContext = cache(async () => {
  /**
   * @see: https://trpc.io/docs/server/context
   */
  // 从cookie中获取token
  try {
    // 尝试获取 headers，如果在请求上下文中
    const headerList = await headers();
    const isAuth = headerList.has("token");
    return {
      token: isAuth ? headerList.get("token") : null,
    };
  } catch (error) {
    // 如果不在请求上下文中，返回空上下文
    return {
      token: null,
    };
  }
});

export type Context = Awaited<ReturnType<typeof createTRPCContext>>;
// Avoid exporting the entire t-object
// since it's not very descriptive.
// For instance, the use of a t variable
// is common in i18n libraries.
const t = initTRPC.context<Context>().create({
  /**
   * @see https://trpc.io/docs/server/data-transformers
   */
  // transformer: superjson,
});
// Base router and procedure helpers
export const createTRPCRouter = t.router;
export const createCallerFactory = t.createCallerFactory;
export const baseProcedure = t.procedure;
